package voidlib;

import models.*;
import db.*;
import java.util.HashMap;
import models.mappers.*;

/**
 *
 * @author nevidimov
 */
public class VoidUser {
    
    private static VoidUser instance = null;
    
    private VoidUser() {
        
    }
    
    public static VoidUser getInstance() {
        if (instance == null) {
            instance = new VoidUser();
        }
        return instance;
    }
    
    public UserRole role;
    public String login;
    
    protected User user = null;
    
    public UserRole getRole() {
        return role;
    }
    public String getLogin() {
        return login;
    }
    
    public static User getCurrent() {
        return getInstance().getUser();
    }
    
    public static int getCurrentId() {
        return getInstance().getId();
    }
    
    public User getUser() {
        if (user == null) {
            if (login == null) {
                return null;
            }
            user = new User().getMapper().fetchOne("login = ?", login);
        }
        return user;
    }
    
    public boolean isGuest() {
        return role == UserRole.Guest;
    }
    
    public int getId() {
        return getUser().getId();
    }
    
    public boolean login(String login, String password) {
        try {
            user = ((UserMapper)new User().getMapper()).getUser(login, password);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        
        if (user != null) {
            VoidController.session.setAttribute("login", login);
            VoidController.session.setAttribute("role", user.getRole());
            this.login = login;
        }
        return user != null;
    }
    
    public void logout() {
        VoidController.session.removeAttribute("login");
        VoidController.session.setAttribute("role", UserRole.Guest);
        
    }
}
